package com.example.demo.config;


import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.BasicDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.example.demo.entity.DataSource;
import com.example.demo.enums.Constants;
import com.example.demo.service.DatasourceService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

@Log4j2
@Configuration
public class DynamicDataSourceConfig {

    @Autowired
    private DatasourceService datasourceService;

    @Autowired
    private javax.sql.DataSource dataSource;

    @Autowired
    private BasicDataSourceCreator basicDataSourceCreator;

    @PostConstruct
    public void refresh(){
        log.info("Refreshing dynamic data sources...");
        this.dynamicDataSource();
    }

    public void dynamicDataSource(){
        try{
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource)dataSource;
        // 配置主数据源
        List<DataSource> sources = datasourceService.getAll();
            log.info("=====>sources"+sources);
        // 从数据库加载动态数据源配置
        for (DataSource dsConfig :sources) {
//            如果非SQL 数据源则跳过
            if(!dsConfig.getType().equals(Constants.DATASOURCE_TYPE_SQL.getCode())) continue;
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            dataSourceProperty.setPoolName(dsConfig.getName());
            dataSourceProperty.setDriverClassName(dsConfig.getDriverClassName());
            dataSourceProperty.setUrl(dsConfig.getUrl());
            dataSourceProperty.setUsername(dsConfig.getUsername());
            dataSourceProperty.setPassword(dsConfig.getPassword());

            javax.sql.DataSource dataSource1 = basicDataSourceCreator.doCreateDataSource(dataSourceProperty);
            log.error("=====>"+dataSource1);
            ds.addDataSource(dsConfig.getName(), dataSource1);
        }
//        日志输出
        log.info("加载动态数据源：{}", ds.getDataSources());
        } catch (Exception e){
            log.error("加载动态数据源失败：{}", e);
        }
    }
}
